package com.ruoyi.groovy.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.groovy.domain.GroovyScriptModel;
import com.ruoyi.groovy.service.GroovyScriptService;
import com.ruoyi.groovy.service.LoadScriptSerivce;
import com.ruoyi.groovy.utils.GroovyUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.ruoyi.groovy.service.impl;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2025-01-13 11:18]
 * @copyright: 2025 echovin.com
 */

@Service
public class LoadScriptSerivceImpl implements CommandLineRunner, LoadScriptSerivce {
    private static final Logger log = LoggerFactory.getLogger(LoadScriptSerivceImpl.class);
    @Resource
    private GroovyScriptService groovyScriptService;
    @Override
    public void run(String... args) throws Exception {
        List<GroovyScriptModel> groovyScriptModels = groovyScriptService.selectAll();
        if (CollectionUtils.isEmpty(groovyScriptModels)){
            return;
        }
        for (GroovyScriptModel groovyScriptModel : groovyScriptModels) {
            String id = groovyScriptModel.getId();
            int type = groovyScriptModel.getType();
            String content = groovyScriptModel.getContent();
            if (StringUtils.isBlank(content)){
                log.error("初始化加载脚本信息失败：无脚本信息:{}", JSON.toJSONString(groovyScriptModel));
                continue;
            }
            try {
                GroovyUtil.loadScript(id, content, type);
            } catch (Exception e) {
                log.error("初始化加载脚本信息异常：{}", JSON.toJSONString(groovyScriptModel), e);
            }
        }
    }

    @Override
    public boolean release(GroovyScriptModel model) {
        if (model == null){
            return false;
        }
        String id = model.getId();
        int type = model.getType();
        String content = model.getContent();
        boolean contains = GroovyUtil.map.containsKey(id);
        try {
            if (contains){
                GroovyUtil.editScript(id, content, type);
            }else{
                GroovyUtil.loadScript(id, content, type);
            }
        } catch (Exception e) {
            log.error("新增或修改时加载脚本信息异常：{}", JSON.toJSONString(model), e);
            return false;
        }
        return true;
    }
}
